package com.vonchenchen.photodemo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.vonchenchen.photodemo.utils.ImageUtils;
import com.vonchenchen.photodemo.utils.StringUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MainActivity extends Activity {

    private Button mPickBtn;
    private Button mTakeBtn;

    //拍照相关
    private final static int CROP = 200;

    //保存裁剪后照片的路径
    private final static String FILE_SAVEPATH = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + "/vonchenchen/Portrait/";

    //保存直接拍照后未经剪裁照片的路径
    private final static String FILE_SAVEPATH_CAMERA = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + "/vonchenchen/Camera/";

    //裁剪后照片的前缀名  文件名：FILE_SAVENAME + timeStamp + ".jpg"
    private final static String FILE_SAVENAME_CROP = "vonchenchen";
    //直接拍照后照片的前缀名   文件名：FILE_SAVENAME_CAMERA + timeStamp + ".jpg"/other
    private final static String FILE_SAVENAME_CAMERA = "vonchenchen";

    private Uri origUri;
    private File protraitFile;
    private Bitmap protraitBitmap;
    private String protraitPath;

    private String theLarge;
    private ImageView mImageView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mPickBtn = (Button) findViewById(R.id.btn_pick);
        mTakeBtn = (Button) findViewById(R.id.btn_take);

        mImageView = (ImageView) findViewById(R.id.iv_photo);

        mPickBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startImagePick();
            }
        });

        mTakeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startTakePhoto();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnIntent) {

        switch (requestCode) {
            case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA: //开启拍照

                //origUri 是我们指定的拍照完毕后存储的uri
                startActionCrop(origUri);                        // 拍照后裁剪
                break;
            case ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP:   //开启选取本地图片
                if(imageReturnIntent != null) {
                    //我们选择完图片后返回其Uri
                    startActionCrop(imageReturnIntent.getData());// 选图后裁剪
                }
                break;
            case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD:  //开启图片剪裁

                boolean b = protraitFile.exists();
                if (!StringUtils.isEmpty(protraitPath) && protraitFile.exists()) {
                    //protraitPath 是我们为裁剪后指定的图片的Uri
                    protraitBitmap = ImageUtils.convertToBitmap(protraitPath, 200, 200);
                    mImageView.setImageBitmap(protraitBitmap);
                }
                break;
        }
    }

    //***********************************************************************
    /**
     * 选择图片
     */
    private void startImagePick() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
        } else {
            //ACTION_PICK 可以显示详细的选择样式
            intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    ImageUtils.REQUEST_CODE_GETIMAGE_BYCROP);
        }
    }

    /**
     * 拍照
     */
    private void startTakePhoto() {
        Intent intent;
        // 判断是否挂载了SD卡
        String savePath = "";
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = FILE_SAVEPATH_CAMERA;
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }

        // 没有挂载SD卡，无法保存文件
        if (StringUtils.isEmpty(savePath)) {
            Toast.makeText(this, "无法保存照片，请检查SD卡是否挂载", Toast.LENGTH_SHORT);
            return;
        }

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());
        String fileName = FILE_SAVENAME_CAMERA + timeStamp + ".jpg";// 照片命名
        File out = new File(savePath, fileName);
        Uri uri = Uri.fromFile(out);
        origUri = uri;

        theLarge = savePath + fileName;// 该照片的绝对路径

        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent,
                ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA);
    }

    /**
     * 拍照后裁剪
     * @param data 原始图片Uri
     */
    private void startActionCrop(Uri data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        //data 这个uri必须经过new File出来
        intent.setDataAndType(data, "image/*");
        //指定裁剪后的图片的保存路径
        intent.putExtra("output", getUploadTempFile(data));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", CROP);// 输出图片大小
        intent.putExtra("outputY", CROP);
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        startActivityForResult(intent,
                ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD);
    }

    /**
     * 在指定裁剪
     * @param uri
     * @return
     */
    private Uri getUploadTempFile(Uri uri) {
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(FILE_SAVEPATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
            Toast.makeText(this, "无法保存上传的头像，请检查SD卡是否挂载", Toast.LENGTH_SHORT).show();
            return null;
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());

        //将uri转换为绝对路径,  如果是file:// 开头的uri，获取路径
        String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(uri);

        // 如果是标准Uri
        if (StringUtils.isEmpty(thePath)) {
            //将uri转换为绝对路径,  如果是content:// 开头的uri，获取路径
            thePath = ImageUtils.getAbsoluteImagePath(this, uri);
        }
        String ext = StringUtils.getFileFormat(thePath);
        ext = StringUtils.isEmpty(ext) ? "jpg" : ext;
        // 裁剪完毕的照片命名
        String cropFileName = FILE_SAVENAME_CROP + timeStamp + "." + ext;
        // 裁剪头像的绝对路径
        protraitPath = FILE_SAVEPATH + cropFileName;
        protraitFile = new File(protraitPath);

        Uri cropUri = Uri.fromFile(protraitFile);
        return cropUri;
    }

}
